//
//  ControlPane;.m
//  iCodeMac
//
//  Created by Andrew Barry on 27/02/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "ControlPanel.h"
#import "FlippedView.h"
#import "JavascriptForm.h"
#import "GenericController.h"
#import "FormEditor.h"
#import "ControlsDataSource.h"

static ControlPanel *sharedPanel;

@implementation ControlPanel
+(ControlPanel *) sharedPanel {
	if (sharedPanel == nil) {
		sharedPanel = [[ControlPanel alloc] init];
	}
	return sharedPanel;
}

+(FormControl *) currentObject {
	return [[ControlPanel sharedPanel] current];
}

+(JavascriptForm *) form {
	ControlPanel *panel = [ControlPanel sharedPanel];
	return panel->form;
}

+(id) valueForProperty: (NSString *) name {
	ControlPanel *panel = [ControlPanel sharedPanel];
	FormControl *object = [ControlPanel currentObject];
	if (object)
		return [object valueForProperty:name];
	else
	{
		FormEditor *editor = [panel->form editor];
		return [editor valueForProperty:name];
	}
}

+(void) setValue: (id) val forProperty:(NSString*) name {
	ControlPanel *panel = [ControlPanel sharedPanel];
	FormControl *object = [ControlPanel currentObject];
	id oldVal;
	
	if (object)
		oldVal = [object valueForProperty: name];
	else
		oldVal = [[panel->form editor] valueForProperty: name];
	
	if ([val isEqual:oldVal])
		return;

	NSArray *data = [NSArray arrayWithObjects:(object != nil ? (id)object : [NSNull null]), val, name, nil];
	[panel->form propChange: data];
}

+(void) updateValue: (id) val forProperty: (NSString *) name forControl: (FormControl *)ctl {
	ControlPanel *panel = [ControlPanel sharedPanel];
	if (ctl == panel->current) {
		[panel->controller updateValue:val forProperty:name];
	}
}

-(void) showForForm: (JavascriptForm *) f {
	if (panel == nil) {
		[NSBundle loadNibNamed:@"Controls" owner:self];
		[panel setFrameAutosaveName: @"icmControlPanel"];
	}
	[controlsDataSource setForm:[f editor]];
	[form autorelease];
	form = [f retain];
	[panel orderFront:self];
}

-(void) hide {
	if (panel != nil)
		[panel orderOut: self];
}

-(void) selectControl: (FormControl *) ctl {
	FlippedView *container = [[FlippedView alloc] init];
	[propsScroller setDocumentView:container];

	[current autorelease];
	current = [ctl retain];
	controller = nil;
	properties = nil;
	if (ctl)
		[NSBundle loadNibNamed:[ctl propsNibName] owner:self];
	else
		[NSBundle loadNibNamed:@"FormProps" owner:self];
	[container setFrame: [properties frame]];
	[container addSubview: properties];
}

-(FormControl *) current {
	return current;
}

+(NSSize) defaultControlSize: (NSString *) controlType {
	if ([controlType isEqualToString:@"box"]) {
		return NSMakeSize(200, 200);
	} else if ([controlType isEqualToString:@"canvas"]) {
		return NSMakeSize(128, 128);
	} else if ([controlType isEqualToString:@"tableview"]
			   || [controlType isEqualToString:@"outlineview"]
			   || [controlType isEqualToString:@"browserview"]) {
		return NSMakeSize(200, 200);
	}

	return NSMakeSize(80, 24);
}


@end
